<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Services\Store;
use App\Services\Common;
use Illuminate\Http\Request;
use Ixudra\Curl\Facades\Curl;
use Intervention\Image\Facades\Image;
use DB;
use SimpleSoftwareIO\QrCode\Facades\QrCode;


class MainController extends Controller
{
	// 售出商品
    public function sellGoods(Request $request){

		$sId = $request->sId;
		$auId = $request->auCode;
        $muId = $request->muCode;
        $sgId = $request->sgId;
        $sgoMemo = $request->sgoMemo;
        $sgoSaleNum = $request->sgoSaleNum;
        $sgoSalePrice = $request->sgoSalePrice;
        $createUser = $request->createUser;
        $sgoPayWay = $request->sgoPayWay;
        $isCustomPrice = $request->isCustomPrice;
        $accountPay = $request->accountPay;
        $cardPay = $request->cardPay;
        $beauticianId = $request->beauticianId;
        $firstBuy = $request->firstBuy;

        $result = $this->common->sellGoods($sId, $auId, $sgId, $sgoSaleNum, $sgoSalePrice,
        					$sgoMemo, $createUser, $muId, $sgoPayWay, $isCustomPrice, $accountPay,
        					$cardPay, $beauticianId, $firstBuy);

        if ($result !== true){
			return $this->returnMsg(0, $result);
		}
		return $this->returnMsg(1, 'OK');
	}

	// 内销商品申请
    public function sellGoodsInside(Request $request){

		$sId = $request->sId;
		$auCode = $request->auCode;
        $sgId = $request->sgId;
        $sgoSaleNum = $request->sgoSaleNum;
        $sgoMemo = $request->sgoMemo;
        $createUser = $request->createUser;

		$sgIdList = explode("|", $sgId);
		$sgoSaleNumList = explode("|", $sgoSaleNum);
		$sgoMemoList = explode("|", $sgoMemo);

		for($i=0;$i<count($sgIdList);$i++){
			DB::table('store_inner_sales')->insert([
				'sId' => $sId,
				'goodsId' => $sgIdList[$i],
				'goodsNum' => $sgoSaleNumList[$i],
				'auCode' => $auCode,
				'remark' => isset($sgoMemoList[$i]) ? $sgoMemoList[$i] : '',
				'createUser' => $createUser,
			]);
		}

		return $this->returnMsg(1, 'OK');
	}

	// 获取商品价格
	public function getGoodsPrice(Request $request){

		$sId = $request->get('sId');
		$sgId = $request->get('sgId');
		$muCode = $request->get('muCode');

		$price = $this->common->getGoodsPrice($sId, $sgId, $muCode);
		if ($price === false){
			return $this->returnMsg(0, '找不到数据对象');
		}

		$minPrice = $this->common->getAmiBottomPrice($sId, $muCode, $sgId);

		$returnPrice = array();
//		print_r($minPrice);exit;
		if (is_array($price)){
			foreach($price as $salePrice){
				$isHave = false;
				foreach($minPrice as $mPrice){
					if ($salePrice->goodsId == $mPrice->goodsId){
						$isHave = true;
						$dataArray = array();
						$dataArray['goodsId'] = $salePrice->goodsId;
						$dataArray['goodsPrice'] = $salePrice->goodsPrice;
						$dataArray['goodsMinPrice'] = isset($mPrice->minPrice)?$mPrice->minPrice:$mPrice->goodsPrice;
						array_push($returnPrice, $dataArray);
						break;
					}
				}
				if (!$isHave){
					$dataArray = array();
					$dataArray['goodsId'] = $salePrice->goodsId;
					$dataArray['goodsPrice'] = $salePrice->goodsPrice;
					$dataArray['goodsMinPrice'] = 0;
					array_push($returnPrice, $dataArray);
				}
			}
		}else{
			$returnPrice['goodsId'] = $sgId;
			$returnPrice['goodsPrice'] = $price;
            $returnPrice['goodsMinPrice'] = $minPrice;
		}
//		$returnPrice = array();
//		$returnPrice['salePrice'] = $price;
//		$returnPrice['minPrice'] = $minPrice;

		return $this->returnMsg(1, 'OK', $returnPrice);
	}

	// 获取用户可买最低价格表
	public function getMinPrice(Request $request){

		$sId = $request->get('sId');
		$muCode = $request->get('muCode');
		$sgId = $request->get('sgId');
		if (!$sgId){
			$sgId = false;
		}

		$result = $this->common->getAmiBottomPrice($sId, $muCode, $sgId);

		return $this->returnMsg(1, 'OK', $result);
	}

	// 获取用户会员卡余额
	public function getAccountMoney(Request $request){

		$sId = $request->get('sId');
		$userCode = $request->get('userCode');

		$result = $this->common->getAccount($sId, $userCode);

		return $this->returnMsg(1, 'OK', $result);
	}

	// 获取店铺进货价
	public function getStorePrice(Request $request){

		$sgId = $request->get('sgId');

		$minPrice = DB::table('agency_goods_price')
						->select(DB::raw('MIN(goodsPrice) AS minPrice'))
						->where('goodsId', $sgId)
						->value('minPrice');

		return $this->returnMsg(1, 'OK', $minPrice);
	}

	// 股东分红
	public function shareBonus(Request $request){

		$sId = $request->get('sId');
		$month = $request->get('month');
		$sbTransferMoney = $request->get('transferMoney');
		$createUser = $request->get('createUser');

		$Store = new Store();

		$result = $Store->shareBonus($sId, $month, $sbTransferMoney, $createUser);
		if ($result === true){
			return $this->returnMsg(1, 'OK');
		}else{
			return $this->returnMsg(0, $result);
		}
	}

	// 获取月份利润
	public function getMonthProfit(Request $request){

		$sId = $request->get('sId');
		$month = $request->get('month');

		$sInfo = DB::table('store')->where('sId', $sId)->first();

		$profit = DB::table('stats_month')
					->where('scId', $sId)
					->where('smMonth', $month)
					->where('smName', 'profit')
					->where('smObjId', $sInfo->sCode)
					->value('smValue');
		if (empty($profit)){
			$profit = 0;
		}
		return $this->returnMsg(1, 'OK', $profit);
	}
    // 更新统计
    public function updateStatic(Request $request){
        $key="09334e1dd5bb8f9bb91dac95f8209da4";
        if($request->token && $request->token==$key){
            if(!$request->sId){
                 return $this->returnMsg(0, '店铺id不存在');
            }else{
                $sId=$request->sId;
                // 统计名单：      流水         成本     利润       新增会员      办卡数      耗卡数     办卡收入    会员卡充值    会员卡消费     会员卡充值人数
                $statsArray = ['flowAccount', 'cost', 'profit', 'newMember', 'timeCard', 'useCard', 'cardFlow', 'recharge', 'consumption', 'rechargeNum'];
                if(in_array($request->static_type,$statsArray)){
                    $Common = new Common();
                    $Common->addStats($sId, $request->static_type, 1, $Common->getScode($sId));
                    return $this->returnMsg(1, '更新统计成功');
                }else{
                   return $this->returnMsg(0, '统计类型不对');
                }
            }
        }else{
            return $this->returnMsg(0, 'token验证失败');
        }
    }

    // 复制店铺，只保留用户：需要先用admin账号创建新店铺
	public function copyStore(Request $request){
		//http://localhost:8084/main/copyStore?sId=10&targetSId=13
		$sId = $request->input('sId');
		$targetSId = $request->input('targetSId');
		$includeActivity = $request->input('includeActivity', false);
		if (!$sId || !$targetSId){
			echo "缺少参数";
			exit;
		}

		// 1.复制店员
		$sql = "INSERT INTO admin_users (username,password,name,avatar,remember_token,phone,sId,spId,alId,auStock,auTotalCashFlow,auTotalProfit,auStatus,auCode,created_at,updated_at)
				SELECT username,password,name,avatar,remember_token,phone, {$targetSId},spId,alId,auStock,auTotalCashFlow,auTotalProfit,auStatus,CONCAT(auCode, 'COPY') AS auCode,created_at,updated_at
				FROM admin_users
				WHERE sId = {$sId}";

		DB::statement($sql);

		// 2.修改身份id
		$auList = DB::table('admin_users')
					->leftJoin('agency_level', 'admin_users.alId', '=', 'agency_level.alId')
					->leftJoin('admin_role_users', 'admin_role_users.user_id', '=', 'admin_users.id')
					->where('admin_users.sId', $sId)
					->get();

		foreach($auList as $auInfo){
			$alInfo = DB::table('agency_level')->where('acId', $targetSId)->where('alLevel', $auInfo->alLevel)->first();
			DB::table('admin_users')->where('sId', $targetSId)->where('auCode', $auInfo->auCode.'COPY')->update(['alId'=>$alInfo->alId]);
		}
//		print_r(json_encode($auList));exit;
		// 3.补充店员角色
		foreach($auList as $auInfo){
			$newAuInfo = DB::table('admin_users')->where('sId', $targetSId)->where('auCode', $auInfo->auCode.'COPY')->first();
			DB::table('admin_role_users')->insert(['role_id'=>$auInfo->role_id, 'user_id'=>$newAuInfo->id]);
		}

		// 4.复制会员
		$sql = "INSERT INTO member_users (mcId,muCode,muNickName,muRealName,muSex,muMobile,muMemo,alId,muAccount,muPoints,mlId,muReferrerName,muReferrerId,muTotalExpend,createUser,createTime,updateUser,updateTime,muCardNum,muBirthday,muBloodType,muAddress,muPassword,openid,needAskId,scores, muLoginDefault, muHeadUrl)
				SELECT {$targetSId}, CONCAT(muCode, 'COPY') AS muCode,muNickName,muRealName,muSex,muMobile,muMemo,alId,muAccount,muPoints,mlId,muReferrerName,CONCAT(muReferrerId, 'COPY') AS muReferrerId,muTotalExpend,createUser,createTime,updateUser,updateTime,muCardNum,muBirthday,muBloodType,muAddress,muPassword,openid,needAskId,scores, muLoginDefault, muHeadUrl
				FROM member_users
				WHERE mcId = {$sId}";
		if (!$includeActivity){
			$sql = "INSERT INTO member_users (mcId,muCode,muNickName,muRealName,muSex,muMobile,muMemo,alId,muAccount,muPoints,mlId,muReferrerName,muReferrerId,muTotalExpend,createUser,createTime,updateUser,updateTime,muCardNum,muBirthday,muBloodType,muAddress,muPassword,openid,needAskId,scores,muLoginDefault, muHeadUrl)
					SELECT {$targetSId}, CONCAT(muCode, 'COPY') AS muCode,muNickName,muRealName,muSex,muMobile,muMemo,alId,muAccount,muPoints,mlId,muReferrerName,CONCAT(muReferrerId, 'COPY') AS muReferrerId,muTotalExpend,createUser,createTime,updateUser,updateTime,muCardNum,muBirthday,muBloodType,muAddress,muPassword,openid,needAskId,scores, muLoginDefault, muHeadUrl
					FROM member_users
					WHERE mcId = {$sId} AND alId > 5";
		}

		DB::statement($sql);

		// 5.修改会员身份id
		$muList = DB::table('member_users')
					->leftJoin('agency_level', 'member_users.alId', '=', 'agency_level.alId')
					->where('member_users.mcId', $sId)
					->get();
		if (!$includeActivity){
			$muList = DB::table('member_users')
					->leftJoin('agency_level', 'member_users.alId', '=', 'agency_level.alId')
					->where('member_users.mcId', $sId)
					->where('member_users.alId', '>', 5)
					->get();
		}

		foreach($muList as $muInfo){
			$alInfo = DB::table('agency_level')->where('acId', $targetSId)->where('alLevel', $muInfo->alLevel)->first();
			DB::table('member_users')
				->where('mcId', $targetSId)
				->where('muCode', $muInfo->muCode.'COPY')
				->where('alId', '>', 5)
				->update(['alId'=>$alInfo->alId]);
		}

		// 6.复制分销关系
		$sql = "INSERT INTO distribution_users (dcId,uId,dlId,duParentId,duParentUid,duGrandId,duGrandUid,duMoney,createUser,createTime,updateUser,updateTime)
				SELECT {$targetSId}, CONCAT(uId, 'COPY') AS uId,dlId,duParentId,CONCAT(duParentUid, 'COPY') AS duParentUid,duGrandId,CONCAT(duGrandUid, 'COPY') AS duGrandUid,0,createUser,createTime,updateUser,updateTime
				FROM distribution_users
				WHERE dcId = {$sId};";

		DB::statement($sql);

		// 7.修正分销关系id
		$sql = "UPDATE distribution_users AS du1
				LEFT JOIN distribution_users AS du2 ON du1.duParentUid = du2.uId
				SET du1.duParentId = du2.duId
				WHERE du1.dcId = {$targetSId};";

		DB::statement($sql);

		$sql = "UPDATE distribution_users AS du1
				LEFT JOIN distribution_users AS du2 ON du1.duGrandUid = du2.uId
				SET du1.duGrandId = du2.duId
				WHERE du1.dcId = {$targetSId};";

		DB::statement($sql);

		// 8.更改以前的用户账号
		$sql = "UPDATE admin_users
				SET username = CONCAT(username, '_OLD')
				WHERE sId = {$sId}";

		DB::statement($sql);

		// 9.更改以前的店铺名
		$sql = "UPDATE store
				SET sName = CONCAT(sName, '_测试')
				WHERE sId = {$sId}";

		DB::statement($sql);

		echo "OK";
	}

	// 获取活动列表
	public function getActivityList(Request $request){

		$sId = $request->input('sId');

		$adList = DB::table('activity_definition')
					->selectRaw("adId, adTitle, adMiniPicUrl, adApplyBeginTime, adApplyEndTime,
									adSiteDescribe, adCurrentPrice, adApplyNum, adViewNum,
									CONCAT('activity/activityView?sId={$sId}&adId=', adId) AS activityUrl")
					->where('acId', $sId)
					->where('adEnable', 1)
					->orderBy('acId')
					->get();

		return $this->returnMsg(1, 'OK', $adList);
	}

	// 获取标签
	public function getUserTags(Request $request){

		$sId = $request->input('sId', 0);
		$Store = new Store();
		$list = $Store->getUserTags($sId);

		return $this->returnMsg(1, 'OK', $list);
	}

	// 取消出库单
	public function channelGoodsOut(Request $request){

		$sgoId = $request->sgoId;
		$operator = $request->operator;

		if (!$operator || !$sgoId){
			return $this->returnMsg(0, '缺少必要参数');
		}

		$Store = new Store();
		$result = $Store->channelGoodsOut($sgoId, $operator);
		if ($result == true){
			return $this->returnMsg(1, 'OK');
		}
		return $this->returnMsg(0, $result);
	}

	// 提现通过
	public function checkWithdraw(Request $request){

		$mwId = $request->mwId;
		$operator = $request->operator;

		if (!$operator || !$mwId){
			return $this->returnMsg(0, '缺少必要参数');
		}

		$mwInfo = DB::Table('member_withdraw')->where('mwId', $mwId)->first();
		if (empty($mwInfo)){
			return $this->returnMsg(0, '找不到对象信息');
		}
		if ($mwInfo->mwStatus == 1){
			return $this->returnMsg(0, '不能重复提现');
		}

		$Store = new Store();
		$Store->addWalletTrade($mwInfo->mcId, 'withdraw', $mwId, '钱包提现', $operator, $mwInfo->muCode, -1*$mwInfo->mwMoney, '');

		DB::Table('member_withdraw')->where('mwId', $mwId)->update(['mwStatus'=>1]);

		return $this->returnMsg(1, 'OK');
	}

	// 内销通过
	public function aggreeConsume(Request $request){

		$sId = $request->sId;
		$sisIds = $request->sisIds;
		$operator = $request->operator;

		$sisIdsArray = explode(",", $sisIds);

		foreach($sisIdsArray as $sisId){
			$sisInfo = DB::table('store_inner_sales')->where('sId', $sId)->where('sisId', $sisId)->first();
			if ($sisInfo->status != 0){
				continue;
			}

        	$auId = $sisInfo->auCode;
        	$sgId = $sisInfo->goodsId;
        	$sgoSaleNum = $sisInfo->goodsNum;
        	$sgoSalePrice = 0;
        	$sgoMemo = '内消';
        	$createUser = $operator;
        	$muId = '';
        	$sgoPayWay = '内消';

        	$result = $this->common->sellGoods($sId, $auId, $sgId, $sgoSaleNum,$sgoSalePrice,
						$sgoMemo, $createUser, $muId, $sgoPayWay);

            if ($result === true){
            	DB::table('store_inner_sales')->where('sisId', $sisId)->update(['status' => 10, 'updateUser' => $operator]);
            }
		}

		return $this->returnMsg(1, 'OK');
	}

	public function getSharePoster(Request $request){
		// Get the current URL without the query string...

		$sId = $request->sId;
		$adId = $request->adId;
		$muCode = $request->muCode;

		$muInfo = DB::table('member_users')->where('mcId', $sId)->where('muCode', $muCode)->first();
		if (empty($muInfo)){
			return $this->returnMsg(0, '系统错误：找不到用户信息');
		}

		$muInfo = json_decode(json_encode($muInfo), true);

//		if (empty($muInfo['muHeadUrl'])){
//			return $this->returnMsg(0, '用户尚未报名活动');
//		}

		$applyInfo = DB::table('activity_apply')
					->where('acId', $sId)
					->where('adId', $adId)
					->where('uId', $muCode)
					->where('aaStats', 1)
					->first();
//		if (empty($applyInfo)){
//			return $this->returnMsg(0, '您还没有报名，无法获取分享海报');
//		}

		$applyInfo = json_decode(json_encode($applyInfo), true);

		$folderPath = "./img/qrcode/{$adId}";
		if (empty($applyInfo)){
			$fileName = $muCode.'.png';
		}else{
			$fileName = $applyInfo['aaId'].'.png';
		}


		if (!file_exists($folderPath.'/'.$fileName)){
			if ($muInfo['muHeadUrl']){
				if (empty($applyInfo)){
					$downloadFile = './download/head/'.$muCode.'.png';
					$useFile = './download/head/'.$muCode.'_wb.png';
				}else{
					$downloadFile = './download/head/'.$applyInfo['aaId'].'.png';
					$useFile = './download/head/'.$applyInfo['aaId'].'_wb.png';
				}
				if (!file_exists($downloadFile)){
					Curl::to($muInfo['muHeadUrl'])->withContentType('image/png')->download($downloadFile);
				}

			    if (!file_exists($useFile)){
			    	$bgFile = './download/head/white.png';
					// open an image file
					$img = Image::make($bgFile);

					// and insert a watermark for example
					$img->insert($downloadFile, 'top-left', 5, 5);
					// finally we save the image as a new file
					$img->save($useFile);
				}
			}

			$thisUrl = route('activityView')."?sId=".$sId."&adId=".$adId;
			$shareUrl = $thisUrl."&referrerCode=".$applyInfo['uId'];

		    if ($muInfo['muHeadUrl']){
				$base64Img = base64_encode(QrCode::format('png')->margin(0.9)->size(230)->merge($useFile, .2, true)->errorCorrection('H')->generate($shareUrl));
			}else{
				$base64Img = base64_encode(QrCode::format('png')->margin(0.9)->size(230)->generate($shareUrl));
			}

	    	$Common = new Common();
	    	$Common->saveBase64Img($base64Img, $folderPath, $fileName);
	    }

	    if ($applyInfo){
	    	$posterFile = './img/qrcode/'.$adId.'/'.$applyInfo['aaId'].'_poster.png';
	    }else{
	    	$posterFile = './img/qrcode/'.$adId.'/'.$muCode.'_poster.png';
	    }

	    if (!file_exists($posterFile)){
			$posterBgFile = './img/qrcode/'.$adId.'/qr_bg.png';
			if (!file_exists($posterBgFile)){
		    	$posterBgFile = './img/qrcode/qr_bg.png';
		    }
			$bgImg = Image::make($posterBgFile);
			$qrImg = Image::make($folderPath.'/'.$fileName);
			$qrImg->resize(120, 120);
			$bgImg->insert($qrImg, 'top-left', 15, 1205);
			$bgImg->save($posterFile);
		}

	    return $this->returnMsg(1, 'OK', 'http://'.$request->server('HTTP_HOST').'/'.$posterFile);
	}

    public function isFirstBuy(Request $request){

        $sId = $request->sId;
        $muCode = $request->muCode;

        $info = DB::table('store_goods_out')
                    ->where('sId', $sId)
                    ->where('muId', $muCode)
                    ->where('sgoIsCancel', 0)
                    ->first();

        if (empty($info)){
            return $this->returnMsg(1, 'OK', 1);
        }

        return $this->returnMsg(1, 'OK', 0);
    }
}
